package com.eastfair.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.common.dto.JYApplyInvoiceInfoDTO;
import com.eastfair.common.dto.JYMainnoResultDTO;
import com.eastfair.common.req.JYReq;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.pay.api.FinanceFeign;
import com.eastfair.pay.dao.InvoiceApplyerMapper;
import com.eastfair.pay.dto.InvoiceApplyerDTO;
import com.eastfair.pay.dto.InvoiceApplyerPageQuery;
import com.eastfair.pay.dto.JYCancelInvoiceDTO;
import com.eastfair.pay.dto.JYInvoiceDTO;
import com.eastfair.pay.entity.*;
import com.eastfair.pay.enums.InvoiceExamineStateEnum;
import com.eastfair.pay.enums.InvoiceStateEnum;
import com.eastfair.pay.enums.PayApproveStateEnum;
import com.eastfair.pay.service.*;
import com.eastfair.pay.vo.InvoiceApplyerVO;
import com.eastfair.projectcore.enumeration.MenuAffiliationEnum;
import com.eastfair.venuebooking.api.ExhibitionSettlementFeign;
import com.eastfair.venuebooking.api.ServiceOrderFeign;
import com.eastfair.venueservice.dto.BizStateDTO;
import com.eastfair.venueservice.dto.ExhibitionSettlementDTO;
import com.eastfair.venueservice.dto.ServiceOrderDTO;
import com.eastfair.venueservice.enumeration.ServiceOrderInvoiceStatusEnum;
import io.seata.common.util.CollectionUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 发票申请
 * </p>
 *
 * @author clm
 * @date 2022-08-06
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class InvoiceApplyerServiceImpl extends SuperServiceImpl<InvoiceApplyerMapper, InvoiceApplyer> implements InvoiceApplyerService {

    @Autowired
    private InvoiceApplyerRelationService invoiceApplyerRelationService;

    @Resource
    private InvoiceService invoiceService;
    @Resource
    private InvoiceTitleService invoiceTitleService;

    @Resource
    private FinanceFeign financeService;
    @Resource
    private ServiceOrderFeign serviceOrderFeign;

    @Resource
    private TransactionOrderService transactionOrderService;

    @Resource
    private ExhibitionSettlementFeign exhibitionSettlementFeign;

    @Value("${com.eastfair.projectId}")
    private Long projectId;

    @Resource
    private DictService dictService;
    @Value("${mice-pay.invoice.ruleId}")
    private String ruleId;

    @Value("${mice-pay.uninvoice.ruleId}")
    private String unRuleId;
    @Resource
    private MerchantSystemService merchantSystemService;

    @Resource
    private InvoiceApplyerMapper invoiceApplyerMapper;

    @Resource
    private JyService jyService;

    /**
     * 基础数据
     *
     * @param model
     * @return
     */
    @Override
    protected R<Boolean> handlerSave(InvoiceApplyer model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTenantId(ContextUtil.getTenantId());
        //雪花ID
        return R.successDef();
    }

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<InvoiceApplyer> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "", magic = @Magic(key = "{" + "{'isEnabled', #args[0]?.isEnabled}," + "{'businessType', #args[0]?.businessType}," + "{'cutomerId', #args[0]?.cutomerId}," + "{'cutomerName', #args[0]?.cutomerName}," + "{'invoiceTitle', #args[0]?.invoiceTitle}," + "{'invoiceDutyParagraph', #args[0]?.invoiceDutyParagraph}," + "{'costType', #args[0]?.costType}," + "{'companyAddress', #args[0]?.companyAddress}," + "{'companyTel', #args[0]?.companyTel}," + "{'exhibitionId', #args[0]?.exhibitionId}," + "{'exhibitionName', #args[0]?.exhibitionName}," + "{'bankAccountNum', #args[0]?.bankAccountNum}," + "{'bankName', #args[0]?.bankName}," + "{'invoiceAmount', #args[0]?.invoiceAmount}," + "{'applicationId', #args[0]?.applicationId}," + "{'applicationName', #args[0]?.applicationName}," + "{'addressee', #args[0]?.addressee}," + "{'toAddress', #args[0]?.toAddress}," + "{'mobile', #args[0]?.mobile}," + "{'mailbox', #args[0]?.mailbox}," + "{'invoiceType', #args[0]?.invoiceType}," + "{'invoiceState', #args[0]?.invoiceState}," + "{'callbackServiceName', #args[0]?.callbackServiceName}," + "{'callbakcApi', #args[0]?.callbakcApi}," + "{'remark', #args[0]?.remark}," + "{'id', #args[1]}" + "}"))
    public List<InvoiceApplyer> listOfCache(InvoiceApplyerDTO modelDTO, List<Long> ids) {
        //查询
        QueryWrapper<InvoiceApplyer> queryWrapper = new QueryWrapper<>();
        if (modelDTO != null) {
            queryWrapper.lambda().eq(Objects.nonNull(modelDTO.getIsEnabled()), InvoiceApplyer::getIsEnabled, modelDTO.getIsEnabled());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getBusinessType()), InvoiceApplyer::getBusinessType, modelDTO.getBusinessType());
            queryWrapper.lambda().eq(modelDTO.getCutomerId() != null, InvoiceApplyer::getCutomerId, modelDTO.getCutomerId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getCutomerName()), InvoiceApplyer::getCutomerName, modelDTO.getCutomerName());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getInvoiceTitle()), InvoiceApplyer::getInvoiceTitle, modelDTO.getInvoiceTitle());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getInvoiceDutyParagraph()), InvoiceApplyer::getInvoiceDutyParagraph, modelDTO.getInvoiceDutyParagraph());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getCostType()), InvoiceApplyer::getCostType, modelDTO.getCostType());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getCompanyAddress()), InvoiceApplyer::getCompanyAddress, modelDTO.getCompanyAddress());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getCompanyTel()), InvoiceApplyer::getCompanyTel, modelDTO.getCompanyTel());
            queryWrapper.lambda().eq(modelDTO.getExhibitionId() != null, InvoiceApplyer::getExhibitionId, modelDTO.getExhibitionId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getExhibitionName()), InvoiceApplyer::getExhibitionName, modelDTO.getExhibitionName());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getBankAccountNum()), InvoiceApplyer::getBankAccountNum, modelDTO.getBankAccountNum());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getBankName()), InvoiceApplyer::getBankName, modelDTO.getBankName());
            queryWrapper.lambda().eq(modelDTO.getApplicationId() != null, InvoiceApplyer::getApplicationId, modelDTO.getApplicationId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getApplicationName()), InvoiceApplyer::getApplicationName, modelDTO.getApplicationName());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getAddressee()), InvoiceApplyer::getAddressee, modelDTO.getAddressee());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getToAddress()), InvoiceApplyer::getToAddress, modelDTO.getToAddress());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getMobile()), InvoiceApplyer::getMobile, modelDTO.getMobile());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getMailbox()), InvoiceApplyer::getMailbox, modelDTO.getMailbox());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getInvoiceType()), InvoiceApplyer::getInvoiceType, modelDTO.getInvoiceType());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getInvoiceState()), InvoiceApplyer::getInvoiceState, modelDTO.getInvoiceState());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getRemark()), InvoiceApplyer::getRemark, modelDTO.getRemark());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getMainno()), InvoiceApplyer::getMainno, modelDTO.getMainno());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getBusinessId()), InvoiceApplyer::getBusinessId, modelDTO.getBusinessId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getBusinessNum()), InvoiceApplyer::getBusinessNum, modelDTO.getBusinessNum());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(InvoiceApplyer::getId, ids);
        }
        queryWrapper.lambda().eq(InvoiceApplyer::getIsDeleted, BusinessConstant.DELETE_NO);
        List<InvoiceApplyer> modelList = list(queryWrapper);
        return modelList;
    }

    /**
     * @param invoiceApplyerDTO
     * @return void
     * @Author clm
     * @Description //保存发票申请
     * @Date 14:51 2022/8/6
     * @Param [invoiceApplyerDTO]
     */
    @Override
    @GlobalTransactional
    public void saveInvoiceApplyer(InvoiceApplyerDTO invoiceApplyerDTO) {
        InvoiceApplyer invoiceApplyer = BeanUtil.copyProperties(invoiceApplyerDTO, InvoiceApplyer.class);

        // 查询交易订单
        TransactionOrder order = transactionOrderService.getByOrderNum(invoiceApplyer.getBusinessNum());
        if (Objects.isNull(order)) {
            throw new BizException("发票关联交易订单不存在,orderNum=" + invoiceApplyer.getBusinessNum());
        }
        // 判断付款时间是否超过了48小时
        // todo 暂时先不加校验
//        if (Duration.between(Objects.isNull(order.getPaymentTime()) ? LocalDateTime.now() : order.getPaymentTime(), LocalDateTime.now()).toHours() < 48) {
//            throw new BizException("支付完成48小时后才可以申请开票");
//        }
        //从交易订单中获取收款单位
        invoiceApplyer.setInvoiceCompany(order.getPayee());
        String systemScene = ContextUtil.getSystemScene();
        invoiceApplyer.setSystemScene(systemScene);
        // 判断开票详情数据是否合法
        checkInvoice(invoiceApplyerDTO);

        invoiceApplyer.setDetails(JSON.toJSONString(invoiceApplyerDTO.getDetails()));
        invoiceApplyer.setExamineState(InvoiceExamineStateEnum.APPLIED.getCode());
        invoiceApplyer.setInvoiceState(InvoiceStateEnum.NOT_INVOICE.getCode());
        invoiceApplyer.setIsEnabled(BusinessConstant.YES);
        invoiceApplyer.setApplicationDate(LocalDateTime.now());
        save(invoiceApplyer);
        log.info("保存发票申请成功,invoiceApplyer={}", invoiceApplyer);
        // 同步业务系统状态
        updateBizExamineState(invoiceApplyer.getId(), Long.parseLong(invoiceApplyerDTO.getBusinessId()));
        log.info("同步业务系统状态成功");
        //发票抬头实例化对象
        InvoiceTitle invoiceTitle = new InvoiceTitle();
        //客户ID
        invoiceTitle.setCutomerId(invoiceApplyer.getCutomerId());
        //对象复制
        BeanUtils.copyProperties(invoiceApplyerDTO, invoiceTitle);
        //查询发票抬头是否存在
        QueryWrapper<InvoiceTitle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(!StrUtil.isBlank(invoiceApplyerDTO.getInvoiceDutyParagraph()), InvoiceTitle::getInvoiceDutyParagraph, invoiceApplyerDTO.getInvoiceDutyParagraph())
                .like(!StrUtil.isBlank(invoiceApplyerDTO.getInvoiceTitle()), InvoiceTitle::getInvoiceTitle, invoiceApplyerDTO.getInvoiceTitle());
        int count = invoiceTitleService.count(queryWrapper);
        //不存在保存发票抬头
        if (count == 0) {
            invoiceTitleService.save(invoiceTitle);
            log.info("保存发票抬头成功,invoiceTitle={}", invoiceTitle);
        }
    }

    /**
     * 计算发票单价数据
     *
     * @param taxRate
     * @param invoiceAmount
     * @param unitPrice
     * @return
     */
    private boolean checkUnitPrice(BigDecimal taxRate, BigDecimal invoiceAmount, BigDecimal unitPrice) {
        if (Objects.isNull(invoiceAmount) || Objects.isNull(taxRate) || Objects.isNull(unitPrice)) {
            return false;
        }
        // 判断单价值是否正确 单价(税前金额) = 税后总价 / (1 + 税率)
        BigDecimal calUnitPrice = invoiceAmount.divide(BigDecimal.ONE.add(taxRate), 2, RoundingMode.HALF_UP);
        return unitPrice.compareTo(calUnitPrice) == 0;
    }

    /**
     * 计算税额数据
     *
     * @param taxRate
     * @param invoiceAmount
     * @param taxAmount
     * @return
     */
    private boolean checkTaxAmount(BigDecimal taxRate, BigDecimal invoiceAmount, BigDecimal taxAmount, String invoiceLineProperty, BigDecimal discountAmount) {
        if (Objects.isNull(invoiceAmount) || Objects.isNull(taxRate) || Objects.isNull(taxAmount)) {
            return false;
        }
        if ("1".equals(invoiceLineProperty)) {
            if (Objects.isNull(discountAmount)) {
                return false;
            }
            // 折扣行
            BigDecimal calTaxAmount = discountAmount.divide(BigDecimal.ONE.add(taxRate), 5, RoundingMode.HALF_UP).multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
            return calTaxAmount.compareTo(taxAmount) == 0;
        }
        // 判断税额值是否正确 税额 = = 税后总价 / (1 + 税率) * 税率
        BigDecimal calTaxAmount = invoiceAmount.divide(BigDecimal.ONE.add(taxRate), 5, RoundingMode.HALF_UP).multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
        return calTaxAmount.compareTo(taxAmount) == 0;
    }


    /**
     * 判断开票详情数据
     *
     * @param invoiceApplyerDTO
     */
    private void checkInvoice(InvoiceApplyerDTO invoiceApplyerDTO) {
        if (!checkInvoiceDutyParagraph(invoiceApplyerDTO.getInvoiceDutyParagraph())) {
            throw new BizException("纳税人识别号格式错误");
        }
        invoiceApplyerDTO.setInvoiceDutyParagraph(invoiceApplyerDTO.getInvoiceDutyParagraph().toUpperCase());
        if (CollectionUtils.isEmpty(invoiceApplyerDTO.getDetails())) {
            throw new BizException("开票详情不能为空");
        }
        // 判断税额0 为0 不予申请
//        boolean flag = invoiceApplyerDTO.getDetails().stream().anyMatch(d -> BigDecimal.ZERO.compareTo(d.getZzse()) < 0);
//        if (flag) {
//            throw new BizException("开票详情中的税额不能小于0");
//        }
        // 判断优惠金额是负数
        if (invoiceApplyerDTO.getDetails().size() == 2) {
            BigDecimal yjse = invoiceApplyerDTO.getDetails().get(0).getZzse();
            BigDecimal jmse = invoiceApplyerDTO.getDetails().get(1).getZzse();
            if (jmse.compareTo(BigDecimal.ZERO) > 0) {
                throw new BizException("减免税额应为负数");
            }
            if (jmse.abs().compareTo(yjse) > 0) {
                throw new BizException("减免税额不能大于应缴税额");
            }
            String bzk = invoiceApplyerDTO.getDetails().get(0).getInvoiceLineProperty();
            String zk = invoiceApplyerDTO.getDetails().get(1).getInvoiceLineProperty();
            if ((!"2".equals(bzk)) || (!"1".equals(zk))) {
                throw new BizException("发票性质不正确");
            }

        } else if (invoiceApplyerDTO.getDetails().size() == 1) {
            String invoiceLineProperty = invoiceApplyerDTO.getDetails().get(0).getInvoiceLineProperty();
            if (!"0".equals(invoiceLineProperty)) {
                throw new BizException("发票性质不正确");
            }
        }
        // 判断单价值是否正确 单价(税前金额) = 税后总价 / (1 + 税率)
//        boolean djFlag = invoiceApplyerDTO.getDetails().stream().filter(m -> (!"1".equals(m.getInvoiceLineProperty())))
//                .anyMatch(d -> {
//                    BigDecimal sl = d.getSl().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
//                    return !checkUnitPrice(sl, invoiceApplyerDTO.getInvoiceAmount(), d.getCpdj());
//                });
//        if (djFlag) {
//            throw new BizException("单价计算异常");
//        }
        // 判断税额值是否正确 税额 = = 税后总价 / (1 + 税率) * 税率
        BigDecimal discountAmount = invoiceApplyerDTO.getDiscountAmount();
        boolean szFlag = invoiceApplyerDTO.getDetails().stream().anyMatch(d -> {
            BigDecimal sl = d.getSl().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
            return !checkTaxAmount(sl, invoiceApplyerDTO.getInvoiceAmount(), d.getZzse(), d.getInvoiceLineProperty(), discountAmount);
        });
        if (szFlag) {
            throw new BizException("税额计算异常");
        }
        log.info("发票校验通过");
    }

    /**
     * @param applyId
     * @return void
     * @Author clm
     * @Description //开票
     * @Date 17:05 2022/8/6
     * @Param [applyId]
     */
    @Override
    public void invoice(Long applyId) {
        InvoiceApplyer invoice = getById(applyId);
        invoice.setInvoiceState(InvoiceStateEnum.INVOICE_SUCCESS.getCode());
        updateById(invoice);
    }

    /**
     * @param params
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.eastfair.pay.vo.InvoiceApplyerVO>
     * @Author clm
     * @Description //分页查询
     * @Date 10:44 2022/8/8
     * @Param [params]
     */
    @Override
    public Page<InvoiceApplyerVO> queryList(PageParams<InvoiceApplyerPageQuery> params) {
        String systemScene = ContextUtil.getSystemScene();
        InvoiceApplyerPageQuery model = params.getModel();
        List<String> scenes = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(model.getSystemScene())) {
            scenes.addAll(model.getSystemScene());
        } else {
            scenes.add(systemScene);
        }
        LambdaQueryWrapper<InvoiceApplyer> invoiceApplyerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        invoiceApplyerLambdaQueryWrapper.eq(model.getCutomerId() != null, InvoiceApplyer::getCutomerId, model.getCutomerId());
        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getInvoiceDutyParagraph()), InvoiceApplyer::getInvoiceDutyParagraph, model.getInvoiceDutyParagraph());
        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getCutomerName()), InvoiceApplyer::getCutomerName, model.getCutomerName());
        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getInvoiceTitle()), InvoiceApplyer::getInvoiceTitle, model.getInvoiceTitle());
        invoiceApplyerLambdaQueryWrapper.eq(StringUtils.isNotBlank(model.getCostType()), InvoiceApplyer::getCostType, model.getCostType());
        invoiceApplyerLambdaQueryWrapper.eq(Objects.nonNull(model.getExhibitionId()), InvoiceApplyer::getExhibitionId, model.getExhibitionId());
        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getExhibitionName()), InvoiceApplyer::getExhibitionName, model.getExhibitionName());
        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getAddressee()), InvoiceApplyer::getAddressee, model.getAddressee());
        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getMobile()), InvoiceApplyer::getMobile, model.getMobile());
        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getMailbox()), InvoiceApplyer::getMailbox, model.getMailbox());
        invoiceApplyerLambdaQueryWrapper.in(InvoiceApplyer::getSystemScene, scenes);
        invoiceApplyerLambdaQueryWrapper.eq(StringUtils.isNotBlank(model.getInvoiceType()), InvoiceApplyer::getInvoiceType, model.getInvoiceType());
        invoiceApplyerLambdaQueryWrapper.eq(StringUtils.isNotBlank(model.getBusinessType()), InvoiceApplyer::getBusinessType, model.getBusinessType());
        invoiceApplyerLambdaQueryWrapper.eq(StringUtils.isNotBlank(model.getExamineState()), InvoiceApplyer::getExamineState, model.getExamineState());
//        invoiceApplyerLambdaQueryWrapper.like(StringUtils.isNotBlank(model.getBusinessNum()), InvoiceApplyer::getBusinessNums, model.getBusinessNum());
        invoiceApplyerLambdaQueryWrapper.eq(model.getApplicationId() != null, InvoiceApplyer::getApplicationId, model.getApplicationId());
        invoiceApplyerLambdaQueryWrapper.like(StrUtil.isNotBlank(model.getApplicationName()), InvoiceApplyer::getApplicationName, model.getApplicationName());
        invoiceApplyerLambdaQueryWrapper.like(StrUtil.isNotBlank(model.getBankAccountNum()), InvoiceApplyer::getBankAccountNum, model.getBankAccountNum());
        invoiceApplyerLambdaQueryWrapper.like(StrUtil.isNotBlank(model.getBankName()), InvoiceApplyer::getBankName, model.getBankName());
        invoiceApplyerLambdaQueryWrapper.like(StrUtil.isNotBlank(model.getMobile()), InvoiceApplyer::getMobile, model.getMobile());
        invoiceApplyerLambdaQueryWrapper.eq(StrUtil.isNotBlank(model.getInvoiceState()), InvoiceApplyer::getInvoiceState, model.getInvoiceState());
        invoiceApplyerLambdaQueryWrapper.eq(StrUtil.isNotBlank(model.getExamineState()), InvoiceApplyer::getExamineState, model.getExamineState());
        invoiceApplyerLambdaQueryWrapper.like(StrUtil.isNotBlank(model.getExaminer()), InvoiceApplyer::getExaminer, model.getExaminer());
        invoiceApplyerLambdaQueryWrapper.eq(model.getExamineId() != null, InvoiceApplyer::getExamineId, model.getExamineId());
        invoiceApplyerLambdaQueryWrapper.eq(StringUtils.isNotBlank(model.getMainno()), InvoiceApplyer::getMainno, model.getMainno());
        invoiceApplyerLambdaQueryWrapper.eq(StringUtils.isNotBlank(model.getBusinessId()), InvoiceApplyer::getBusinessId, model.getBusinessId());
        invoiceApplyerLambdaQueryWrapper.eq(StringUtils.isNotBlank(model.getBusinessNum()), InvoiceApplyer::getBusinessNum, model.getBusinessNum());
        invoiceApplyerLambdaQueryWrapper.like(StrUtil.isNotBlank(model.getInvoiceCompany()), InvoiceApplyer::getInvoiceCompany, model.getInvoiceCompany());

        //参数转化
        Page<InvoiceApplyer> applyerPage = params.buildPage();
        //查询
        Page<InvoiceApplyer> applyer = page(applyerPage, invoiceApplyerLambdaQueryWrapper);
        //实体转化
        Page<InvoiceApplyerVO> invoiceApplyerVOPage = ConvertUtil.convertPage(applyer, InvoiceApplyerVO.class);
        return invoiceApplyerVOPage;
    }

    /**
     * @param invoiceApplyerId
     * @return com.eastfair.pay.vo.InvoiceApplyerVO
     * @Author clm
     * @Description //获取发票申请详情
     * @Date 18:13 2023/2/7
     * @Param [businessId]
     */
    @Override
    public InvoiceApplyerVO queryInfoById(Long invoiceApplyerId) {
        InvoiceApplyer invoiceApplyer = baseMapper.selectById(invoiceApplyerId);
        InvoiceApplyerVO invoiceApplyerVO = BeanUtil.copyProperties(invoiceApplyer, InvoiceApplyerVO.class);
        return invoiceApplyerVO;
    }

    /**
     * @param buinessId
     * @return com.eastfair.pay.vo.InvoiceApplyerVO
     * @Author clm
     * @Description //通过业务主键获取发票申请
     * @Date 15:05 2023/2/8
     * @Param [buinessId]
     */
    @Override
    public InvoiceApplyerVO queryInfoByBuinessId(Long buinessId) {
        QueryWrapper<InvoiceApplyer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id", buinessId);
        queryWrapper.eq("is_enabled", BusinessConstant.YES);
        queryWrapper.eq("is_deleted", BusinessConstant.DELETE_NO);
        InvoiceApplyer invoiceApplyer = baseMapper.selectOne(queryWrapper);
        if (invoiceApplyer == null) {
            return null;
        }
        InvoiceApplyerVO invoiceApplyerVO = BeanUtil.copyProperties(invoiceApplyer, InvoiceApplyerVO.class);
        return invoiceApplyerVO;
    }

    /**
     * @param invoiceApplyerDTO
     * @return void
     * @Author clm
     * @Description //审核
     * @Date 11:34 2023/2/14
     * @Param [invoiceApplyer]
     */
    @Override
    @GlobalTransactional
    public void examineInvoiceApplyer(InvoiceApplyerDTO invoiceApplyerDTO) {
        //查询发票申请记录
        InvoiceApplyer invoiceApplyer = baseMapper.selectById(invoiceApplyerDTO.getId());
        log.info("查询发票申请记录,id={} invoiceApplyer={}", invoiceApplyerDTO.getId(), invoiceApplyer);
        if (invoiceApplyer == null) {
            throw new BizException("发票申请记录不存在");
        }
        //更新发票审核信息
        invoiceApplyer.setExaminer(invoiceApplyerDTO.getExaminer());
        invoiceApplyer.setExamineReason(invoiceApplyerDTO.getExamineReason());
        invoiceApplyer.setExamineId(invoiceApplyerDTO.getExamineId());
        //审核通过 对接荆艺发票申请
        if (PayApproveStateEnum.PAY_APPROVED.equals(PayApproveStateEnum.get(invoiceApplyerDTO.getPayApproveState()))) {
            JYReq<JYApplyInvoiceInfoDTO> applyInvoiceDTO = jyService.buildApplyInvoiceToJy(invoiceApplyer);
            //调荆艺接口申请开票
            log.info("申请荆艺开票入参，req={}", applyInvoiceDTO);
            R<List<JYMainnoResultDTO>> result = financeService.sync(applyInvoiceDTO);
            log.info("申请荆艺开票出参，result={}", result);
            if (result != null && result.getIsSuccess()) {
                if (CollectionUtils.isNotEmpty(result.getData())) {
                    invoiceApplyer.setExamineState(InvoiceExamineStateEnum.INVOICING.getCode());
                    invoiceApplyer.setInvoiceState(InvoiceStateEnum.INVOICING.getCode());
                    invoiceApplyer.setMainno(result.getData().get(0).getMainno());
                }
            } else {
                log.error("申请荆艺开票失败,result={}", result);
                throw new BizException("审核失败");
            }
        } else {
            // 驳回
            invoiceApplyer.setExamineState(InvoiceExamineStateEnum.REJECT.getCode());
            invoiceApplyer.setIsEnabled(BusinessConstant.NO);
        }
        updateById(invoiceApplyer);
        log.info("更新开票申请成功, invoiceApplyer={}", invoiceApplyer);
        // 同步业务系统状态
        updateBizExamineState(invoiceApplyer.getId(), Long.parseLong(invoiceApplyer.getBusinessId()));
        log.info("同步业务系统状态成功");

    }

    @Override
    @GlobalTransactional
    public void cancelInvoiceApplyer(Long id) {
        //查询发票申请记录
        InvoiceApplyer invoiceApplyer = baseMapper.selectById(id);
        log.info("查询发票申请记录,id={} invoiceApplyer={}", id, invoiceApplyer);
        if (invoiceApplyer == null) {
            throw new BizException("发票申请记录不存在");
        }
        if (!InvoiceExamineStateEnum.INVOICING.getCode().equals(invoiceApplyer.getExamineState())) {
            throw BizException.wrap(-1, "发票申请不在开具中，不可取消");
        }
        if (StringUtils.isEmpty(invoiceApplyer.getMainno())) {
            throw BizException.wrap(-1, "发票申请缺少开票流水号");
        }
        JYReq<JYCancelInvoiceDTO> applyInvoiceDTO = jyService.buildCancelInvoiceToJy(invoiceApplyer);
        //调荆艺接口申请开票
        log.info("申请荆艺取消开票入参，req={}", applyInvoiceDTO);
        R<List<JYMainnoResultDTO>> result = financeService.sync(applyInvoiceDTO);
        log.info("申请荆艺取消开票出参，result={}", result);
        if (result != null && result.getIsSuccess()) {
            invoiceApplyer.setInvoiceState(InvoiceStateEnum.INVOICE_CANCEL.getCode());
            invoiceApplyer.setExamineState(InvoiceExamineStateEnum.INVOICE_CANCEL.getCode());
            invoiceApplyer.setIsEnabled(BusinessConstant.NO);
            updateById(invoiceApplyer);
            log.info("取消开票申请成功, invoiceApplyer={}", invoiceApplyer);
            // 同步业务系统状态
            updateBizExamineState(invoiceApplyer.getId(), Long.parseLong(invoiceApplyer.getBusinessId()));
            log.info("同步业务系统状态成功");
        } else {
            log.error("调用荆艺取消开票失败,result={}", result);
            throw BizException.wrap("取消开票失败");
        }


    }

    @Override
    public void cancelInvoiceApplyerByOrderNum(String orderNum) {
        //查询发票申请记录
        InvoiceApplyer invoiceApplyer = lambdaQuery().eq(InvoiceApplyer::getBusinessNum, orderNum)
                .eq(InvoiceApplyer::getIsDeleted, BusinessConstant.DELETE_NO).eq(InvoiceApplyer::getIsEnabled, BusinessConstant.ENABLE_YES).one();
        log.info("查询发票申请记录,orderNum={} invoiceApplyer={}", orderNum, invoiceApplyer);
        if (invoiceApplyer == null) {
            throw new BizException("发票申请记录不存在");
        }
        if (!InvoiceExamineStateEnum.INVOICING.getCode().equals(invoiceApplyer.getExamineState())) {
            throw BizException.wrap(-1, "发票申请不在开具中，不可取消");
        }
        if (StringUtils.isEmpty(invoiceApplyer.getMainno())) {
            throw BizException.wrap(-1, "发票申请缺少开票流水号");
        }
        JYReq<JYCancelInvoiceDTO> applyInvoiceDTO = jyService.buildCancelInvoiceToJy(invoiceApplyer);
        //调荆艺接口申请开票
        log.info("申请荆艺取消开票入参，req={}", applyInvoiceDTO);
        R<List<JYMainnoResultDTO>> result = financeService.sync(applyInvoiceDTO);
        log.info("申请荆艺取消开票出参，result={}", result);
        if (result != null && result.getIsSuccess()) {
            invoiceApplyer.setInvoiceState(InvoiceStateEnum.INVOICE_CANCEL.getCode());
            invoiceApplyer.setExamineState(InvoiceExamineStateEnum.INVOICE_CANCEL.getCode());
            invoiceApplyer.setIsEnabled(BusinessConstant.NO);
            updateById(invoiceApplyer);
            log.info("取消开票申请成功, invoiceApplyer={}", invoiceApplyer);
            // 同步业务系统状态
            updateBizExamineState(invoiceApplyer.getId(), Long.parseLong(invoiceApplyer.getBusinessId()));
            log.info("同步业务系统状态成功");
        } else {
            log.error("调用荆艺取消开票失败,result={}", result);
            throw BizException.wrap("取消开票失败");
        }
    }

    /**
     * @param invoiceApplyerDTO
     * @return void
     * @Author clm
     * @Description //更新
     * @Date 17:58 2023/2/17
     * @Param [invoiceApplyerDTO]
     */
    @Override
    public void updateInvoiceApplyer(InvoiceApplyerDTO invoiceApplyerDTO) {
        InvoiceApplyer invoiceApplyer = BeanUtil.copyProperties(invoiceApplyerDTO, InvoiceApplyer.class);
        updateById(invoiceApplyer);
    }

    /**
     * @return void
     * @Author fwl
     * @Description //荆艺开票审核
     * @Date 11:32 2023/3/3
     * @Param [invoiceApplyerDTO]
     **/
    @Override
    @GlobalTransactional
    public void financialExamine(JYInvoiceDTO invoiceDTO) {
        if (invoiceDTO.getMainno() == null || invoiceDTO.getInvoiceState() == null || invoiceDTO.getIsFlushRed() == null) {
            throw new BizException("参数不合法");
        }
        ContextUtil.setProjectId(projectId);
        if (invoiceDTO.getIsFlushRed()) {
            // 冲红票
            if (InvoiceStateEnum.INVOICE_FAIL.getCode().equals(invoiceDTO.getInvoiceState())) {
                log.error("冲红票开具失败,invoice={}", invoiceDTO);
            } else {
                if (StringUtils.isEmpty(invoiceDTO.getSourceInvoiceNum())) {
                    throw new BizException("参数不合法");
                }
                // 根据原发票代码和原发票号码 查询原来的申请记录号
                List<Invoice> invoiceList = invoiceService.lambdaQuery()
//                        .eq(Invoice::getInvoiceCode, invoiceDTO.getSourceInvoiceCode())
                        .eq(Invoice::getInvoiceNum, invoiceDTO.getSourceInvoiceNum())
                        .eq(Invoice::getIsFlushRed, BusinessConstant.NO)
                        .eq(Invoice::getIsDeleted, BusinessConstant.DELETE_NO)
                        .eq(Invoice::getIsEnabled, BusinessConstant.YES)
                        .orderByDesc(Invoice::getInvoicingTime).list();
                if (CollectionUtils.isEmpty(invoiceList)) {
                    log.error("未找到原始票据,invoice={}", invoiceDTO);
                    throw new BizException("未找到冲红票据的原始票据");
                } else {
                    Long applicantId = invoiceList.get(0).getInvoiceApplyId();
                    InvoiceApplyer invoiceApplyer = baseMapper.selectById(applicantId);
                    invoiceApplyer.setExamineState(InvoiceExamineStateEnum.INVOICE_RED.getCode());
                    invoiceApplyer.setIsEnabled(BusinessConstant.NO);
                    invoiceApplyer.setInvoiceState(InvoiceStateEnum.INVOICE_SUCCESS.getCode());
                    updateById(invoiceApplyer);
                    log.info("冲红票据修改原始申请记录成功");
                    // 同步业务系统状态
                    updateBizExamineState(invoiceApplyer.getId(), Long.parseLong(invoiceApplyer.getBusinessId()));
                    log.info("冲红票同步业务系统成功");
                    Invoice invoice = new Invoice();
                    invoice.setProjectId(invoiceApplyer.getProjectId());
                    invoice.setTenantId(invoiceApplyer.getTenantId());
                    invoice.setInvoiceType(invoiceApplyer.getInvoiceType());
                    invoice.setInvoiceCode(invoiceDTO.getInvoiceCode());
                    invoice.setInvoiceNum(invoiceDTO.getInvoiceNum());
                    invoice.setInvoiceAmount(invoiceDTO.getInvoiceAmount());
                    invoice.setInvoicingTime(invoiceDTO.getInvoicingTime());
                    invoice.setInvoiceState(InvoiceStateEnum.INVOICE_SUCCESS.getCode());
                    invoice.setCostType(invoiceApplyer.getCostType());
                    invoice.setSystemCode(invoiceApplyer.getSystemScene());
                    invoice.setInvoiceApplyId(invoiceApplyer.getId());
                    invoice.setIsFlushRed(BusinessConstant.YES);
                    invoice.setSourceInvoiceCode(invoiceDTO.getSourceInvoiceCode());
                    invoice.setSourceInvoiceNum(invoiceDTO.getSourceInvoiceNum());
                    invoice.setInvoiceLink(invoiceDTO.getInvoiceLink());
                    invoiceService.save(invoice);
                    log.info("冲红票开票成功,invoice={}", invoice);
                }

            }
        } else {
            // 非冲红票
            List<InvoiceApplyer> list = lambdaQuery().eq(InvoiceApplyer::getMainno,invoiceDTO.getMainno()).eq(InvoiceApplyer::getIsDeleted,BusinessConstant.DELETE_NO)
                    .eq(InvoiceApplyer::getIsEnabled,BusinessConstant.ENABLE_YES).list();
            if (CollectionUtils.isEmpty(list)) {
                throw new BizException("开票申请单号不存在");
            }
            InvoiceApplyer invoiceApplyer = list.get(0);
            log.info("开票申请查询,invoiceApplyer={}", invoiceApplyer);
            if (InvoiceStateEnum.INVOICE_SUCCESS.getCode().equals(invoiceApplyer.getInvoiceState())) {
                throw new BizException("该开票申请单已开票成功");
            }
            if (InvoiceStateEnum.INVOICE_SUCCESS.getCode().equals(invoiceDTO.getInvoiceState())) {
                // 成功
                invoiceApplyer.setExamineState(InvoiceExamineStateEnum.INVOICE_SUCCESS.getCode());
                invoiceApplyer.setInvoiceState(InvoiceStateEnum.INVOICE_SUCCESS.getCode());
                Invoice invoice = new Invoice();
                invoice.setProjectId(invoiceApplyer.getProjectId());
                invoice.setTenantId(invoiceApplyer.getTenantId());
                invoice.setInvoiceType(invoiceApplyer.getInvoiceType());
                invoice.setInvoiceCode(invoiceDTO.getInvoiceCode());
                invoice.setInvoiceNum(invoiceDTO.getInvoiceNum());
                invoice.setInvoiceAmount(invoiceDTO.getInvoiceAmount());
                invoice.setInvoicingTime(invoiceDTO.getInvoicingTime());
                invoice.setInvoiceState(InvoiceStateEnum.INVOICE_SUCCESS.getCode());
                invoice.setCostType(invoiceApplyer.getCostType());
                invoice.setSystemCode(invoiceApplyer.getSystemScene());
                invoice.setInvoiceApplyId(invoiceApplyer.getId());
                invoice.setIsFlushRed(BusinessConstant.NO);
                invoice.setInvoiceLink(invoiceDTO.getInvoiceLink());
                invoiceService.save(invoice);
                log.info("非冲红开票成功,invoice={}", invoice);
            } else {
                // 失败
                invoiceApplyer.setExamineState(InvoiceExamineStateEnum.INVOICE_FAIL.getCode());
                invoiceApplyer.setIsEnabled(BusinessConstant.NO);
            }
            updateById(invoiceApplyer);
            log.info("非冲红票据修改原始申请记录成功");
            // 同步业务系统状态
            updateBizExamineState(invoiceApplyer.getId(), Long.parseLong(invoiceApplyer.getBusinessId()));
            log.info("非冲红票同步业务系统成功");
        }
    }

    /**
     * 同步业务系统 申请状态
     *
     * @param id
     */
    public void updateBizExamineState(Long id, Long businessId) {
        Map<String, String> map = new HashMap<>();
        map.put("INVOICE_RED", "INVOICE_RED");
        map.put("INVOICE_CANCEL", "INVOICE_CANCEL");
        map.put("INVOICE_FAIL", "INVOICE_FAIL");
        map.put("INVOICING", "INVOICING");
        map.put("REJECT", "REJECTED");
        map.put("INVOICE_SUCCESS", "INVOICED");
        map.put("APPLIED", "REQUESTED");
        //查询发票申请记录
        LambdaQueryWrapper<InvoiceApplyer> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(id)) {
            queryWrapper.eq(InvoiceApplyer::getId, id);
        } else {
            queryWrapper.eq(Objects.nonNull(businessId), InvoiceApplyer::getBusinessId, businessId);
            queryWrapper.eq(InvoiceApplyer::getIsEnabled, BusinessConstant.YES);
        }
        InvoiceApplyer invoiceApplyer = baseMapper.selectOne(queryWrapper);

        log.info("查询发票申请记录,id={} invoiceApplyer={}", id, invoiceApplyer);
        if (invoiceApplyer == null) {
            throw new BizException("发票申请记录不存在");
        }
        MenuAffiliationEnum anEnum = MenuAffiliationEnum.get(invoiceApplyer.getSystemScene());
        log.info("归属系统:{},订单号:{},开票状态:{}", invoiceApplyer.getSystemScene(), invoiceApplyer.getBusinessId(), invoiceApplyer.getExamineState());
        switch (anEnum) {
            case P_COMPOSITE_VENUE:
            case P_COMPOSITE_COURT:
            case P_COMPOSITE_PRODUCER:
            case P_COMPOSITE_TRANSPORT:
            case P_COMPOSITE_MATING:
                // 业务类型#{H:合同;J:结算单;G:管理费订单;D:服务订单;Z:证件订单;}
                // todo 待完善
                switch (invoiceApplyer.getBusinessType()) {
                    case "J":
                        ExhibitionSettlementDTO settlementDTO = new ExhibitionSettlementDTO();
                        settlementDTO.setId(Long.parseLong(invoiceApplyer.getBusinessId()));
                        settlementDTO.setInvoicingStatus(map.get(invoiceApplyer.getExamineState()));
                        exhibitionSettlementFeign.updateSettlement(settlementDTO);
                        break;
                    case "H":
                        break;
                    case "G":
                    case "D":
                        // 管理费、服务订单
                        ServiceOrderDTO serviceOrderDTO = new ServiceOrderDTO();
                        serviceOrderDTO.setOrderNumber(invoiceApplyer.getBusinessNum());
                        serviceOrderDTO.setId(Long.parseLong(invoiceApplyer.getBusinessId()));
                        serviceOrderDTO.setInvoiceStatus(ServiceOrderInvoiceStatusEnum.get(map.get(invoiceApplyer.getExamineState())));
                        if (InvoiceStateEnum.INVOICE_SUCCESS.getCode().equals(invoiceApplyer.getInvoiceState())) {
                            // 开票成功 回传 开票金额,发票代码,发票号码
                            List<Invoice> list = invoiceService.lambdaQuery().eq(Invoice::getInvoiceApplyId, invoiceApplyer.getId()).eq(Invoice::getIsDeleted, BusinessConstant.DELETE_NO).orderByDesc(Invoice::getCreateTime).list();
                            serviceOrderDTO.setInvoiceAmount(list.get(0).getInvoiceAmount());
                            serviceOrderDTO.setInvoiceCode(list.get(0).getInvoiceCode());
                            serviceOrderDTO.setInvoiceNumber(list.get(0).getInvoiceNum());
                        }
                        serviceOrderFeign.updateInvoiceStatus(serviceOrderDTO);
                        break;
                    case "Z":
                        break;
                    default:
                        log.info("未知业务类型");
                }
                break;
            default:
                log.info("未同步的系统:{},订单号:{},开票状态:{}", invoiceApplyer.getSystemScene(), invoiceApplyer.getBusinessId(), invoiceApplyer.getExamineState());
        }
    }

    public void updateBizRefundState(InvoiceApplyerDTO invoiceApplyerDTO) {
        // 判断是审核通过还是不通过
        String examineState = invoiceApplyerDTO.getPayApproveState();
        if (StringUtils.isBlank(examineState)) {
            InvoiceApplyer invoiceApplyer = getById(invoiceApplyerDTO.getId());
            // 交给综合系统处理
            try {
                List<InvoiceApplyerRelation> list = invoiceApplyerRelationService.list(new QueryWrapper<InvoiceApplyerRelation>().lambda().eq(InvoiceApplyerRelation::getIsDeleted, BusinessConstant.DELETE_NO).eq(InvoiceApplyerRelation::getIsEnabled, BusinessConstant.YES).eq(InvoiceApplyerRelation::getApplyId, invoiceApplyerDTO.getId()));
                for (InvoiceApplyerRelation invoiceApplyerRelation : list) {
                    BizStateDTO BizStateDTO = BeanUtil.copyProperties(invoiceApplyer, BizStateDTO.class);
                    BizStateDTO.setBusinessId(invoiceApplyerRelation.getBusinessId());
                    R<Boolean> booleanR = serviceOrderFeign.updateBizInvoiceApplyState(BizStateDTO);
                    if (!booleanR.getIsSuccess()) {
                        throw BizException.wrap(booleanR.getCode(), booleanR.getMsg());
                    }
                }

            } catch (Exception e) {
                throw e;
            }
        }
    }

    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public InvoiceApplyerVO doToVo(InvoiceApplyer model) {
        InvoiceApplyerVO modelVo = new InvoiceApplyerVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<InvoiceApplyerVO> doToVos(List<InvoiceApplyer> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<InvoiceApplyerVO> result = new ArrayList<>();
        for (InvoiceApplyer model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<InvoiceApplyer> list(InvoiceApplyerDTO modelDTO, List<Long> ids) {
        return null;
    }

    @Override
    public List<InvoiceApplyerVO> queryInvoiceExamineState(List<Long> buinessIds) {
        log.info("参数：buinessIds={}", buinessIds);
        if (CollectionUtils.isEmpty(buinessIds)) {
            throw new BizException("参数不合法");
        }
        List<InvoiceApplyer> modelList = invoiceApplyerMapper.queryInvoiceExamineStateByIds(buinessIds.stream().map(Object::toString).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(modelList)) {
            return Lists.newArrayList();
        } else {
            return modelList.stream().map(m -> {
                InvoiceApplyerVO invoiceApplyerVO = new InvoiceApplyerVO();
                invoiceApplyerVO.setBusinessId(m.getBusinessId());
                invoiceApplyerVO.setExamineState(m.getExamineState());
                // 这是场馆业务系统需要的字段 （开票单位 开票金额 发票类型 申请时间）
                invoiceApplyerVO.setId(m.getId());
                invoiceApplyerVO.setInvoiceTitle(m.getInvoiceTitle());
                invoiceApplyerVO.setInvoiceCompany(m.getInvoiceCompany());
                invoiceApplyerVO.setInvoiceAmount(m.getInvoiceAmount());
                invoiceApplyerVO.setInvoiceType(m.getInvoiceType());
                invoiceApplyerVO.setApplicationDate(m.getApplicationDate());
                return invoiceApplyerVO;
            }).collect(Collectors.toList());
        }
    }

    /**
     * 校验纳税人识别号
     *
     * @param invoiceDutyParagraph
     * @return
     */
    private boolean checkInvoiceDutyParagraph(String invoiceDutyParagraph) {
        if (StringUtils.isEmpty(invoiceDutyParagraph)) {
            return false;
        }
        String pattern = "^[A-Z0-9]{15}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(invoiceDutyParagraph.toUpperCase());
        return m.matches();
    }
}
